﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using ArunimaErp.Domain;
using ArunimaErp.Models;
using System.Drawing;

namespace ArunimaErp.Controllers
{
    [Authorize(Roles = "DprEntry")]
    public class DprController : Controller
    {
        private arunimaEntities db = new arunimaEntities();
        UserAccountRepository userAccountRepository = new UserAccountRepository();

        #region Common

        public JsonResult GetSelectedStyle(int id)
        {
            var styleinfo = db.styleinfo.Where(ps => ps.BuyerId == id).ToList();

            var styleData = styleinfo.Select(c => new SelectListItem()
            {
                Text = c.StyleNo,
                Value = c.StyleId.ToString()
            });

            return Json(styleData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetSelectedPo(int id)
        {
            var poInfo = db.postyle.Where(ps => ps.StyleId == id).ToList();

            var poData = poInfo.Select(c => new SelectListItem()
            {
                Text = c.PoNo,
                Value = c.PoStyleId.ToString()
            });

            return Json(poData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetOrderQuantity(int id)
        {
            var postyle = db.postyle.Where(p => p.PoStyleId == id);

            var orderQuantity = postyle.Select(s => new { s.OrderQuantity });

            return Json(orderQuantity, JsonRequestBehavior.AllowGet);
        }


        #endregion

        #region Index
        //
        // GET: /Dpr/
        public ActionResult Index()
        {
            var allDpr = db.productiondailyreport.ToList();
            return View(allDpr);
        }

        /// <summary>
        /// Returns data by the criterion
        /// </summary>
        /// <param name="param">Request sent by DataTables plugin</param>
        /// <returns>JSON text used to display data
        /// <list type="">
        /// <item>sEcho - same value as in the input parameter</item>
        /// <item>iTotalRecords - Total number of unfiltered data. This value is used in the message:
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>iTotalDisplayRecords - Total number of filtered data. This value is used in the message:
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>aoData - Twodimensional array of values that will be displayed in table.
        /// Number of columns must match the number of columns in table and number of rows is equal to the number of records that should be displayed in the table</item>
        /// </list>
        /// </returns>

        public ActionResult AjaxHandler(JQueryDataTableParamModel param)
        {          
            var allDpr = db.productiondailyreport.ToList();
 
            IEnumerable<productiondailyreport> filteredDpr;
            
            //Check whether the companies should be filtered by keyword
            if (!string.IsNullOrEmpty(param.sSearch))
            {
                filteredDpr = db.productiondailyreport.ToList()
                       .Where(c => c.postyle.PoNo.ToLower().Contains(param.sSearch.ToLower())
                       ||
                       c.postyle.styleinfo.StyleNo.ToLower().Contains(param.sSearch.ToLower())
                       ||
                       c.Date.ToString("MMM-dd-yyyy").Contains(param.sSearch.ToLower())
                       );
            }
            else
            {
                filteredDpr = allDpr;
            }

            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
            Func<productiondailyreport, string> orderingFunction = (c => sortColumnIndex == 1 ? c.postyle.PoNo : "");

            var sortDirection = Request["sSortDir_0"]; // asc or desc
            if (sortDirection == "asc")
                filteredDpr = filteredDpr.OrderBy(orderingFunction);
            else
                filteredDpr = filteredDpr.OrderByDescending(orderingFunction);

            var displayedCompanies = filteredDpr.Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var result = from d in displayedCompanies
                         select new[] {
                            Convert.ToString(d.ProductionDailyReportId), d.Date.ToString("MMM-dd-yyyy"), d.Hour.ToString(),
                            d.postyle.PoNo, d.postyle.styleinfo.StyleNo,
                            d.Floor, d.Line,
                            d.Cutting.ToString(), d.SewingInput.ToString(), d.TodaySewing.ToString(),
                            d.SentPrintEmb.ToString(), d.ReceivedPrintEmb.ToString(), d.SentWash.ToString(),
                            d.ReceivedWash.ToString(), d.TodayFinish.ToString(), d.TodaySewingTarget.ToString()
                        };

            return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = allDpr.Count(),
                    iTotalDisplayRecords = filteredDpr.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region Create

        //
        // GET: /Dpr/Create

        public ActionResult Create()
        {
            ViewBag.BuyerId = new SelectList(db.buyerinfo, "BuyerId", "BuyerName");
            
            return View();
        }

        //
        // POST: /Dpr/Create

        [HttpPost]
        public JsonResult Create(productiondailyreport dpr)
        {
            if (ModelState.IsValid)
            {
                db.productiondailyreport.Add(dpr);
                db.SaveChanges();

                return Json(JsonResponseFactory.SuccessResponse(dpr), JsonRequestBehavior.DenyGet);
            }

            var errorList = (from item in ModelState.Values
                             from error in item.Errors
                             select error.ErrorMessage).ToList();

            return Json(JsonResponseFactory.ErrorResponse(errorList), JsonRequestBehavior.DenyGet); 
        }

        #endregion

        #region Edit
        //
        // GET: /Dpr/Edit/5

        public ActionResult Edit(int id)
        {
            productiondailyreport dpr = db.productiondailyreport.Single(p => p.ProductionDailyReportId == id);

            ViewBag.BuyerId = new SelectList(db.buyerinfo, "BuyerId", "BuyerName", dpr.postyle.styleinfo.BuyerId);
            ViewBag.StyleId = new SelectList(db.styleinfo, "StyleId", "StyleNo", dpr.postyle.StyleId);
            ViewBag.PoStyleId = new SelectList(db.postyle.Where(x=>x.StyleId==dpr.postyle.StyleId), "PoStyleId", "PoNo", dpr.PoStyleId);
            return View(dpr);
        }

        //
        // POST: /Dpr/Edit/5

        [HttpPost]
        public ActionResult Edit(productiondailyreport dpr)
        {
            if (ModelState.IsValid)
            {
                //db.productiondailyreport.Attach(dpr);
                db.Entry(dpr).State = EntityState.Modified;
                db.SaveChanges();
                return Json(JsonResponseFactory.SuccessResponse(dpr), JsonRequestBehavior.DenyGet);
            }

            var errorList = (from item in ModelState.Values
                             from error in item.Errors
                             select error.ErrorMessage).ToList();

            return Json(JsonResponseFactory.ErrorResponse(errorList), JsonRequestBehavior.DenyGet); 
        }

        #endregion

        #region Delete
        //
        // GET: /Dpr/Delete/5

        //[Authorize(Roles = "DprEntry")]
        //public ActionResult Delete(int id)
        //{
        //    productiondailyreport productiondailyreport = db.productiondailyreport.Single(p => p.ProductionDailyReportId == id);
        //    return View(productiondailyreport);
        //}

        ////
        //// POST: /Dpr/Delete/5

        //[HttpPost, ActionName("Delete")]
        //[Authorize(Roles = "DprEntry")]
        //public JsonResult DeleteConfirmed(int id)
        //{
        //    productiondailyreport productiondailyreport = db.productiondailyreport.Single(p => p.ProductionDailyReportId == id);
        //    db.productiondailyreport.Remove(productiondailyreport);
        //    db.SaveChanges();
        //    return Json(JsonResponseFactory.SuccessResponse(productiondailyreport), JsonRequestBehavior.DenyGet);
        //}
        #endregion

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}